<template>
  <div class="balance-records-container">
    <div class="page-header">
      <h1>余额明细</h1>
      <div class="breadcrumb">
        <a href="/account" class="breadcrumb-item">我的账户</a>
        <i class="el-icon-arrow-right"></i>
        <a class="breadcrumb-item active">余额明细</a>
      </div>
    </div>

    <el-card class="search-filter-card">
      <div class="search-filters">
        <div class="filter-row">
          <el-input
              v-model="searchParams.keyword"
              placeholder="搜索订单号或交易描述"
              prefix-icon="el-icon-search"
              class="filter-input"
          />
          <el-select
              v-model="searchParams.type"
              placeholder="交易类型"
              class="filter-select"
          >
            <el-option label="全部类型" value=""></el-option>
            <el-option label="账户充值" value="RECHARGE"></el-option>
            <el-option label="课程购买" value="PAYMENT"></el-option>
            <el-option label="退款" value="REFUND"></el-option>
            <el-option label="系统赠送" value="GIFT"></el-option>
          </el-select>
          <el-select
              v-model="searchParams.status"
              placeholder="交易状态"
              class="filter-select"
          >
            <el-option label="全部状态" value=""></el-option>
            <el-option label="交易成功" value="SUCCESS"></el-option>
            <el-option label="处理中" value="PROCESSING"></el-option>
            <el-option label="交易失败" value="FAILED"></el-option>
            <el-option label="待支付" value="PENDING"></el-option>
          </el-select>
          <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              class="filter-date-picker"
          />
        </div>
        <div class="filter-actions">
          <el-button type="primary" @click="searchRecords">查询</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </div>
      </div>
    </el-card>

    <el-card class="records-summary-card">
      <div class="summary-stats">
        <div class="stat-item">
          <div class="stat-label">总收入</div>
          <div class="stat-value income">+¥{{ statistics.totalIncome.toFixed(2) }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">总支出</div>
          <div class="stat-value expense">-¥{{ Math.abs(statistics.totalExpense).toFixed(2) }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">净收入</div>
          <div
              class="stat-value"
              :class="{ income: statistics.netIncome > 0, expense: statistics.netIncome < 0 }"
          >
            {{ statistics.netIncome > 0 ? '+' : '' }}¥{{ statistics.netIncome.toFixed(2) }}
          </div>
        </div>
        <div class="stat-item">
          <div class="stat-label">交易笔数</div>
          <div class="stat-value">{{ statistics.totalCount }}</div>
        </div>
      </div>
    </el-card>

    <el-card class="records-table-card">
      <template #header>
        <div class="table-header">
          <span>交易记录列表</span>
          <span v-if="loading" class="loading-text">加载中...</span>
        </div>
      </template>
      <el-table
          v-loading="loading"
          :data="balanceRecords"
          style="width: 100%"
          border
      >
        <el-table-column prop="created_at" label="交易时间" width="200">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="交易类型" width="120">
          <template #default="scope">
            <el-tag
                :type="getTypeTagType(scope.row.record_type)"
                size="small"
            >
              {{ getRecordType(scope.row.record_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="交易描述" min-width="200">
          <template #default="scope">
            {{ scope.row.business_desc || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="交易金额" width="120" align="right">
          <template #default="scope">
            <span
                :class="{ income: scope.row.amount > 0, expense: scope.row.amount < 0 }"
            >
              {{ scope.row.amount > 0 ? '+' : '' }}{{ scope.row.amount.toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="balance_after" label="交易后余额" width="120" align="right">
          <template #default="scope">
            {{ scope.row.balance_after.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="交易状态" width="120">
          <template #default="scope">
            <el-tag
                :type="getStatusTagType(scope.row.status)"
                size="small"
            >
              {{ getRecordStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="订单号" min-width="180">
          <template #default="scope">
            {{ scope.row.transaction_no || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="scope">
            <el-button
                type="text"
                size="small"
                @click="viewRecordDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { useAccountStore } from '@/stores/account/account';
import type { BalanceRecord } from '@/types/account/Account';

const accountStore = useAccountStore();

// 搜索参数
const searchParams = reactive({
  keyword: '',
  type: '',
  status: '',
  startDate: '',
  endDate: ''
});

// 日期范围选择器
const dateRange = ref<[Date, Date] | null>(null);

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
});

// 加载状态
const loading = ref(false);

// 余额记录列表
const balanceRecords = ref<BalanceRecord[]>([]);

// 统计信息
const statistics = reactive({
  totalIncome: 0,
  totalExpense: 0,
  netIncome: 0,
  totalCount: 0
});

/**
 * 获取交易类型标签
 */
const getRecordType = (type: string): string => {
  const types = {
    'RECHARGE': '账户充值',
    'CONSUME': '课程购买', // 注意这里类型定义中是CONSUME，不是PAYMENT
    'REFUND': '退款',
    'GIFT': '系统赠送',
    'FROZEN': '冻结', // 添加类型定义中存在的类型
    'UNFROZEN': '解冻' // 添加类型定义中存在的类型
  };
  return types[type as keyof typeof types] || '其他';
};

/**
 * 获取交易类型标签样式
 */
const getTypeTagType = (type: string): string => {
  const typeTags = {
    'RECHARGE': 'success',
    'CONSUME': 'danger', // 注意这里类型定义中是CONSUME，不是PAYMENT
    'REFUND': 'warning',
    'GIFT': 'primary',
    'FROZEN': 'info', // 添加类型定义中存在的类型
    'UNFROZEN': 'info' // 添加类型定义中存在的类型
  };
  return typeTags[type as keyof typeof typeTags] || 'default';
};

/**
 * 获取交易状态标签
 */
const getRecordStatus = (status: string): string => {
  const statuses = {
    'SUCCESS': '交易成功',
    'PROCESSING': '处理中',
    'FAILED': '交易失败',
    'PENDING': '待支付'
  };
  return statuses[status as keyof typeof statuses] || '未知状态';
};

/**
 * 获取交易状态标签样式
 */
const getStatusTagType = (status: string): string => {
  const statusTags = {
    'SUCCESS': 'success',
    'PROCESSING': 'warning',
    'FAILED': 'danger',
    'PENDING': 'info'
  };
  return statusTags[status as keyof typeof statusTags] || 'default';
};

/**
 * 格式化日期时间
 */
const formatDateTime = (timeString: string): string => {
  try {
    const date = new Date(timeString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch {
    return timeString;
  }
};

/**
 * 搜索记录
 */
const searchRecords = () => {
  // 更新日期范围
  if (dateRange.value) {
    searchParams.startDate = new Date(dateRange.value[0]).toISOString().split('T')[0];
    searchParams.endDate = new Date(dateRange.value[1]).toISOString().split('T')[0];
  } else {
    searchParams.startDate = '';
    searchParams.endDate = '';
  }

  // 重置页码
  pagination.page = 1;

  // 查询记录
  fetchBalanceRecords();
};

/**
 * 重置筛选条件
 */
const resetFilters = () => {
  searchParams.keyword = '';
  searchParams.type = '';
  searchParams.status = '';
  searchParams.startDate = '';
  searchParams.endDate = '';
  dateRange.value = null;
  pagination.page = 1;

  fetchBalanceRecords();
};

/**
 * 处理页面大小变化
 */
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.page = 1;
  fetchBalanceRecords();
};

/**
 * 处理页码变化
 */
const handleCurrentChange = (current: number) => {
  pagination.page = current;
  fetchBalanceRecords();
};

/**
 * 查看记录详情
 */
const viewRecordDetail = (record: BalanceRecord) => {
  // 这里可以实现查看记录详情的逻辑，例如打开弹窗或跳转到详情页
  ElMessage.info(`查看记录ID: ${record.id} 的详情`);
};

/**
 * 获取余额记录列表
 */
const fetchBalanceRecords = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchParams,
      page: pagination.page,
      pageSize: pagination.pageSize
    };

    const response = await accountStore.fetchBalanceRecords(params);

    console.log('BalanceRecordsView response:', response); // 调试日志

    if (response && (response.list || response.records)) {
      // 兼容后端返回的数据结构（可能是records或list）
      balanceRecords.value = response.list || response.records;
      pagination.total = response.total || 0;
      
      console.log('balanceRecords.value:', balanceRecords.value); // 调试日志
      console.log('pagination.total:', pagination.total); // 调试日志

      // 计算统计数据
      calculateStatistics();
    } else {
      console.log('No data found in response'); // 调试日志
    }
  } catch (error) {
    ElMessage.error('获取余额记录失败');
    console.error('获取余额记录失败:', error);
  } finally {
    loading.value = false;
  }
};

/**
 * 计算统计数据
 */
const calculateStatistics = () => {
  const records = balanceRecords.value;

  // 初始化统计数据
  statistics.totalIncome = 0;
  statistics.totalExpense = 0;
  statistics.totalCount = records.length;

  // 计算收入和支出
  records.forEach(record => {
    if (record.amount > 0) {
      statistics.totalIncome += record.amount;
    } else {
      statistics.totalExpense += record.amount;
    }
  });

  // 计算净收入
  statistics.netIncome = statistics.totalIncome + statistics.totalExpense;
};

// 初始化加载数据
fetchBalanceRecords();
</script>

<style scoped>
.balance-records-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 10px;
}

.breadcrumb {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #909399;
}

.breadcrumb-item {
  color: #909399;
  text-decoration: none;
}

.breadcrumb-item.active {
  color: #667eea;
}

.breadcrumb i {
  margin: 0 10px;
  font-size: 12px;
}

.search-filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.search-filters {
  padding: 20px;
}

.filter-row {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.filter-input {
  width: 300px;
}

.filter-select {
  width: 180px;
}

.filter-date-picker {
  width: 300px;
}

.filter-actions {
  margin-top: 16px;
  display: flex;
  gap: 12px;
}

.records-summary-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.summary-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  padding: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}
</style>